package assist.client.gwt.view.place;

import java.util.Date;

import assist.domain.model.GamesQuery;
import assist.domain.model.Team;

import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;

public class SelectGamesPlace extends Place
{
    public static class Tokenizer implements PlaceTokenizer<SelectGamesPlace>
    {

        @Override
        public SelectGamesPlace getPlace(String token)
        {
            return new SelectGamesPlace(createGamesQuery(token));
        }

        @Override
        public String getToken(SelectGamesPlace place)
        {
            return createToken(place.gamesQuery);
        }
    }

    public static GamesQuery createGamesQuery(String token)
    {
        GamesQuery gamesQuery = new GamesQuery();
        String [] params = token.split("&");
        for(String param: params)
        {
            String [] nameValue = param.split("=");
            if (nameValue[0].equals("start"))
            {
                gamesQuery.setStart(new Date(new Long(nameValue[1])));
            }
            else if (nameValue[0].equals("end"))
            {
                gamesQuery.setEnd(new Date(new Long(nameValue[1])));
            }
            else if (nameValue[0].equals("team"))
            {
                System.err.println("TODO: SelectGamesPlace Need a Teamprovider/Factory to fill in missing team fields");                
                Team team = new Team();
                team.setAbbreviation(nameValue[1]);
                gamesQuery.setTeam(team);
            }
        }
        return gamesQuery;
    }
    
    private GamesQuery gamesQuery;
    
    public SelectGamesPlace(GamesQuery gamesQuery)
    {
        this.gamesQuery = gamesQuery;
    }

    public GamesQuery getGamesQuery()
    {       
        return this.gamesQuery;
    }

    public static String createToken(GamesQuery gamesQuery)
    {
        return "start=" + gamesQuery.getStart().getTime()  
               + "&" + "end=" + gamesQuery.getEnd().getTime()
               + "&" + "team=" + gamesQuery.getTeam().getAbbreviation();

    } 
}
